import router from '../router'
import cookie from 'vue-cookies'
import store from '../store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式

const whiteList = ['/login', '/404']

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (cookie.get('token')) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (!store.getters.role) {
        store.dispatch('getUserInfo').then(res => {
          const role = res.role
          store.dispatch('getPermissionRoutes', role).then(res => {
            router.addRoutes(res)
            next({ ...to, replace: true }) // replace属性为true的时候可以让链接在跳转的时候不会留下历史记录
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
